package com.iwhalecloud.bss.kite.cucc.service.pos.handler.impl;

import com.google.common.collect.Lists;
import com.iwhalecloud.bss.kite.common.constant.ErrorConsts;
import com.iwhalecloud.bss.kite.common.util.KiteDateUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosAttrDTO;
import com.iwhalecloud.bss.kite.cucc.client.dto.pos.KitePosDeveloperDTO;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.KitePosHandlerContext;
import com.iwhalecloud.bss.kite.cucc.service.util.ChangeTypeUtils;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.ztesoft.bss.common.util.SpringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class KitePosDeveloperHandler extends KitePosSceneHandler {

    @Override
    public void handle(KitePosHandlerContext context) {
        IQuerySceneInstService querySceneInstService = SpringUtil.getBean(IQuerySceneInstService.class);
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(context.getSceneInstId());
        String offerId = querySceneInstService.getOfferInst(kiteSceneInst.getCustId(), kiteSceneInst.getRootInstId()).getOfferId();
        String provinceNbr = kiteSceneInst.getProvinceNbr();
        if (StringUtils.equalsAny(kiteSceneInst.getOperType(), LocalKeyConsts.SCENE_OPER_TYPE_ORDER_SIGN)) {
            return;
        }
        if (KiteStringUtils.equalsAny(kiteSceneInst.getServiceOfferId(), LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_ADD, LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_DEL)) {
            context.getPosDto().setDeveloper(null);
            return;
        }
        String cateId = CuccPosServiceUtils.getCateId(context.getSceneInstId(), context.getCustId());
        String createDateStr = KiteDateUtils.formatDate(kiteSceneInst.getCreateDate(), KiteDateUtils.DATE_TIME_FORMAT_14);
        String serviceOfferId = (String) Optional
                .ofNullable(querySceneInstService.getSceneInst(context.getSceneInstId()))
                .map(KiteSceneInst::getServiceOfferId).orElse("");
        //收入归集集团成员加入、退出没有Developer节点
        if(KiteStringUtils.equalsAny(serviceOfferId, LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_ADD, LocalServiceOfferConsts.SERVICE_OFFER_COLLECTION_GROUP_DEL)){
            return;
        }
        KitePosDeveloperDTO oldDeveloper = querySceneInstService
                .getExtParameterValue(context.getSceneInstId(), "developer");
        List<KiteAttr> publicAttrs = querySceneInstService.listCommonAttrsByModuleId(context.getSceneInstId(), LocalKeyConsts.MODULE_ID_PUBLIC);
        // 收入归集集团创建和批量归集集团创建的公共信息操作栏模块id为204114(北京除外)
        if(KiteStringUtils.isNotBlank(offerId) && "10002239".equals(offerId) && !"11".equals(provinceNbr)){
            publicAttrs = querySceneInstService.listCommonAttrsByModuleId(context.getSceneInstId(), LocalKeyConsts.MODULE_ID_PUBLIC_GJJT);
        }
        KiteAttr developerAttrObj = publicAttrs.stream().filter(attr -> KiteStringUtils.equals(attr.getFieldName(), "devPersonInfo")).findFirst().orElse(null);
        if(Objects.isNull(developerAttrObj)) {
            KitePosDeveloperDTO developer = context.getPosDto().getDeveloper();
            if (Objects.nonNull(developer) && KiteStringUtils.isEmpty(developer.getChangeType()) && CuccPosServiceUtils.isProdModify(context.getSceneInstId())) {
                //非新购场景且没有changeType才赋值为9
                developer.setChangeType(ChangeTypeUtils.CHANGE_TYPE_K);
            }
            return ;
        }
        else {
            List<KiteAttr> developerAttrs = querySceneInstService.listCommonAttrsByModuleId(context.getSceneInstId(), LocalKeyConsts.MODULE_ID_DEVELOPER);
            // 收入归集集团创建和批量归集集团创建的发展人模块id为621-(北京除外)
            if(KiteStringUtils.isNotBlank(offerId) && "10002239".equals(offerId) && !"11".equals(provinceNbr)){
                developerAttrs = querySceneInstService.listCommonAttrsByModuleId(context.getSceneInstId(), LocalKeyConsts.MODULE_ID_DEVELOPER_GJJT);
            }
            if (KiteListUtils.isEmpty(developerAttrs)) {
                if (LocalServiceOfferConsts.SERVICE_OFFER_FOLLOW.equals(serviceOfferId)) {
                    KitePosDeveloperDTO developer = context.getPosDto().getDeveloper();
                    if (Objects.nonNull(developer) && KiteStringUtils.isEmpty(developer.getChangeType())) {
                        developer.setChangeType(ChangeTypeUtils.CHANGE_TYPE_K);
                    }
                    return;
                }
                else {
                    ErrorConsts.BUSI_COMMON_ERROR.throwOut("未配置【发展人】属性");
                }
            }
            KitePosDeveloperDTO developer = new KitePosDeveloperDTO();
            developer.setStaffId(this.getAttrValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_ID, "未配置【发展人员工ID】属性"));
            developer.setChannelId(this.getAttrValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_CHANNELID, "未配置【发展人渠道ID】属性"));
            developer.setDepartId(this.getAttrValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_CHANNELID, "未配置【发展人部门】属性"));
            developer.setChannelName(this.getAttrValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_CHANNELNAME, "未配置【发展人渠道名称】属性"));
            developer.setName(this.getAttrValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_NAME, "未配置【发展人名称】属性"));
            developer.setPhone(this.getAttrValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_TEL, "未配置【发展人联系方式】属性"));
            developer.setEmail(this.getAttrValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_EMAIL, "未配置【发展人邮箱】属性"));
            String isSendSms = this.getAttrValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_SENDMESSAGE, "未配置【是否发送短信】属性");
            // 【是否发送短信】属性获取为空时默认0-否
            if (KiteStringUtils.isEmpty(isSendSms)) {
                developer.setIsSendSms("0");
            } else {
                developer.setIsSendSms(isSendSms);
            }
            // 云账号注册增加发展人省份
            if (KiteStringUtils.equalsAny(cateId, "2000998", "2100982", "2100983")) {
                if (Objects.isNull(developer.getAttrs())) {
                    developer.setAttrs(Lists.newArrayList());
                }
                // 发展人省份
//                    KitePosAttrDTO developProvince = new KitePosAttrDTO();
//                    developProvince.setCode("developProvince");
//                    developProvince.setValue(Optional.ofNullable(this.getAttrValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_PROV, "未配置【发展人省份】属性")).orElse(""));
//                    developProvince.setStartDate(createDateStr);
//                    developProvince.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
//                    developer.getAttrs().add(developProvince);
            }
            /*
             * 对接用户中心改造：需要新增changeType、startTime、endTime字段
             */
            if(CuccPosServiceUtils.isRouteUser(context.getSceneInstId(),context.getCustId())) {
                if(!KiteStringUtils.equals(developerAttrObj.getValue(), "T")) {
                    // 未选中的情况下，判断是否存在旧值，存在则说明此次操作非订购需删除，不存在则说明此次不调整代理商。
                    if(KiteStringUtils.isEmpty(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_ID, ""))) {
                        if( KiteStringUtils.isEmpty(developer.getStaffId()) && Objects.isNull(oldDeveloper)){
                            context.getPosDto().setDeveloper(null);
                        }else {
                            context.getPosDto().setDeveloper(developer);
                        }
                        return ;
                    }
                    developer.setStaffId(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_ID, "未配置【发展人员工ID】属性"));
                    developer.setChannelId(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_CHANNELID, "未配置【发展人渠道ID】属性"));
                    developer.setDepartId(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_CHANNELID, "未配置【发展人部门】属性"));
                    developer.setChannelName(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_CHANNELNAME, "未配置【发展人渠道名称】属性"));
                    developer.setName(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_NAME, "未配置【发展人名称】属性"));
                    developer.setPhone(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_TEL, "未配置【发展人联系方式】属性"));
                    developer.setIsSendSms(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_SENDMESSAGE, "未配置【是否发送短信】属性"));
                    if(Objects.nonNull(oldDeveloper)) {
                        developer.setStartTime(oldDeveloper.getStartTime());
                        // developer.setEndTime(oldDeveloper.getEndTime());
                        // 删除发展人信息endTime字段设为当前时间
                        String nowtime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());
                        developer.setEndTime(nowtime);
                    }
                    developer.setChangeType(ChangeTypeUtils.CHANGE_TYPE_D);
                }else {
                    // 非订购的情况下，需要传changeType、startTime、endTime字段
                    if (CuccPosServiceUtils.isProdModify(context.getSceneInstId())) {
                        if(KiteStringUtils.isEmpty(this.getAttrOriginValueValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_ID, ""))) {
                            developer.setChangeType(ChangeTypeUtils.CHANGE_TYPE_A);
                        }else {
                            if(Objects.nonNull(oldDeveloper)) {
                                developer.setStartTime(oldDeveloper.getStartTime());
                                developer.setEndTime(oldDeveloper.getEndTime());
                            }

                            if(KiteStringUtils.equals(serviceOfferId, "2826")) {
                                String nodeCode = querySceneInstService.getExtParameterValue(context.getSceneInstId(), "nodeCode");
                                if(KiteStringUtils.equals(nodeCode, "OrderSigned")) {
                                    // 产品变更-签订，设置真正的originValue，以便对比changeType
                                    updateOrderSignedSetChangeType(oldDeveloper, developer);
                                }
                            }

                            List<KiteAttr> changeKiteAttr = developerAttrs.stream().filter(attr -> !KiteStringUtils.equals(attr.getOriginValue(), attr.getValue())).collect(Collectors.toList());
                            if(KiteListUtils.isEmpty(changeKiteAttr)) {
                                developer.setChangeType(ChangeTypeUtils.CHANGE_TYPE_K);
                                List<KitePosAttrDTO> attrLists = getDeveloperAttr(developerAttrs,createDateStr);
                                developer.setAttrs(attrLists);
                            }else {
                                developer.setChangeType(ChangeTypeUtils.CHANGE_TYPE_M);
                                List<KitePosAttrDTO> attrLists = getDeveloperAttr(developerAttrs,createDateStr);
                                developer.setAttrs(attrLists);
                            }
                        }
                    } else {
                        // 订购，资源核查等情况
                        if (KiteStringUtils.isEmpty(developer.getChangeType())) {
                            developer.setChangeType(ChangeTypeUtils.CHANGE_TYPE_A);
                        }
                    }
                }
            }
            if( KiteStringUtils.isEmpty(developer.getStaffId()) && Objects.isNull(oldDeveloper)){
                context.getPosDto().setDeveloper(null);
            }else {
                context.getPosDto().setDeveloper(developer);
            }
        }

    }

    public List<KitePosAttrDTO> getDeveloperAttr(List<KiteAttr> developerAttrs, String createDateStr) {
        List<KitePosAttrDTO> attrLists = new ArrayList<>();
        for (KiteAttr developerAttr : developerAttrs) {
            KitePosAttrDTO kitePosAttrDTO = new KitePosAttrDTO();
            kitePosAttrDTO.setChangeType(KiteStringUtils.equals(developerAttr.getValue(), developerAttr.getOriginValue()) ? ChangeTypeUtils.CHANGE_TYPE_K : ChangeTypeUtils.CHANGE_TYPE_M);

            if (KiteStringUtils.equals(LocalKeyConsts.DEVPERSON_INFO_ID, developerAttr.getFieldName())) {
                kitePosAttrDTO.setCode("staffId");
            }
            if (KiteStringUtils.equals(LocalKeyConsts.DEVPERSON_INFO_CHANNELID, developerAttr.getFieldName())) {
                kitePosAttrDTO.setCode("channelId");
            }
            if (KiteStringUtils.equals(LocalKeyConsts.DEVPERSON_INFO_CHANNELNAME, developerAttr.getFieldName())) {
                kitePosAttrDTO.setCode("channelName");
            }
            if (KiteStringUtils.equals(LocalKeyConsts.DEVPERSON_INFO_NAME, developerAttr.getFieldName())) {
                kitePosAttrDTO.setCode("name");
            }
            if (KiteStringUtils.equals(LocalKeyConsts.DEVPERSON_INFO_TEL, developerAttr.getFieldName())) {
                kitePosAttrDTO.setCode("phone");
            }
            if (KiteStringUtils.equals(LocalKeyConsts.DEVPERSON_INFO_EMAIL, developerAttr.getFieldName())) {
                kitePosAttrDTO.setCode("email");
            }
            if (KiteStringUtils.equals(LocalKeyConsts.DEVPERSON_INFO_SENDMESSAGE, developerAttr.getFieldName())) {
                kitePosAttrDTO.setCode("isSendSms");
                if (KiteStringUtils.isEmpty(developerAttr.getValue())) {
                    developerAttr.setValue("0");
                }
            }
            if (KiteStringUtils.equals(LocalKeyConsts.DEVPERSON_INFO_PROV, developerAttr.getFieldName())) {
                kitePosAttrDTO.setCode("developProvince");
                developerAttr.setValue(Optional.ofNullable(this.getAttrValue(developerAttrs, LocalKeyConsts.DEVPERSON_INFO_PROV, "未配置【发展人省份】属性")).orElse(""));
            }
            kitePosAttrDTO.setEndDate(LocalKeyConsts.ATTR_SEND_DATE);
            kitePosAttrDTO.setStartDate(createDateStr);
            if(StringUtils.isEmpty(developerAttr.getOriginValue())&&StringUtils.isNotEmpty(developerAttr.getValue())){
                kitePosAttrDTO.setChangeType(ChangeTypeUtils.CHANGE_TYPE_A);
            }
            kitePosAttrDTO.setValue(developerAttr.getValue());
            kitePosAttrDTO.setOriginValue(developerAttr.getOriginValue());
            kitePosAttrDTO.setType("STRING");
            attrLists.add(kitePosAttrDTO);
        }
        return attrLists;
    }

    /**
     * 变更操作，若有签订环节，签订时，需对比当前值与用户信息值确定changeType，当前默认对比的订单信息查询接口返回的值，在此处理，设置originValue
     */
    private static void updateOrderSignedSetChangeType(KitePosDeveloperDTO oldDeveloper, KitePosDeveloperDTO developer) {
        if(oldDeveloper == null || developer == null) {
            return;
        }
        List<KitePosAttrDTO> oldAttrs = oldDeveloper.getAttrs();
        List<KitePosAttrDTO> attrs = developer.getAttrs();
        if(KiteListUtils.isEmpty(oldAttrs) || KiteListUtils.isEmpty(attrs)) {
            return;
        }

        for (KitePosAttrDTO oldAttr : oldAttrs) {
            for (KitePosAttrDTO attr : attrs) {
                if(KiteStringUtils.equals(oldAttr.getCode(), attr.getCode())) {
                    attr.setOriginValue(oldAttr.getOriginValue());
                    break;
                }
            }
        }
    }
}
